import config from "./config";
//@ts-ignore
import fetchajaxgettext from "./fetchajaxgettext.cjs";
import { generateinitialdata } from "./generateinitialdata";
import { getabsolutecatalogue } from "./getbaseurl";
import { precheckfetchajaxmarkdown } from "./precheckfetchajaxmarkdown";
import { StateType } from "./StateType";
// import { states } from "./states";
import { urlclearhashandsearch } from "./urlclearhashandsearch";

export async function commoninitialize(states: StateType) {
    const catalogueurl: string = getabsolutecatalogue();
    const { baseurl } = config;
    // alert(catalogueurl);
    var path = catalogueurl;
    path = urlclearhashandsearch(path);
    const rawdata: string = await fetchajaxgettext(path);
    const { cachetitle, menulist, catalogue } = await generateinitialdata(
        catalogueurl,
        rawdata,
        baseurl
    );
    // const tmpdoc = document.implementation.createHTMLDocument("");

    // tmpdoc.body.innerHTML = markedhtml;
    // const doccontainer = tmpdoc.body;
    // changeimgsrc(doccontainer, catalogueurl);
    // const tmpcontainer = document.createElement("div");

    // tmpdoc.body.childNodes.forEach((n) => tmpcontainer.appendChild(n));
    // //删除当中的style标签和link标签和script标签
    // removesomevalidelements(tmpcontainer);

    // const codeelements = tmpcontainer.querySelectorAll("pre code");
    // const { default: highlightcodeormath } = await import(
    //     "./highlightcodeormath"
    // );
    // for (let element of codeelements) {
    //     await highlightcodeormath(element, path);
    // }
    // const homefile: string = getabsoluteindex();
    // menulist.unshift(homefile);
    // rawcatalogue.unshift({ link: homefile, text: config.maintitle });

    // const hometitle = config.maintitle;
    // addlinkhomeandsummary(
    //     /* catalogueurl,  */ homefile,
    //     tmpcontainer,
    //     hometitle
    // );

    // changelinkmd(states, tmpcontainer, catalogueurl, menulist);

    // //删除重复的链接
    // removerepeatlinks(tmpcontainer);
    // // addlinkclasslist(tmpcontainer);
    // removeallvalidelements(tmpcontainer);
    // const leftmuluhtmlcontent = tmpcontainer.innerHTML;

    // if (!cachemain.get(path)) {
    //     cachemain.set(path, leftmuluhtmlcontent);
    // }

    // Object.freeze(menulist);
    // console.log("menulist", menulist);

    if (process.env.browser && !process.env.PRERENDER) {
        menulist.forEach((path: string) => {
            precheckfetchajaxmarkdown(path);
        });
    }
    states.menulist = menulist;
    states.catalogue = catalogue;
    Array.from(cachetitle.entries()).forEach(([key, value]) => {
        states.cachetitle.set(key, value);
    });
}
